<?php

/**
 * This is the model class for table "advice".
 *
 * The followings are the available columns in table 'advice':
 * @property string $id
 * @property string $name
 * @property string $type
 * @property integer $upload
 * @property integer $weight
 * @property integer $time_upload
 * @property integer $time_create
 * @property integer $time_update
 */
class Advice extends CActiveRecord
{

    const UPLOAD_UPLOAD = 1;
    const UPLOAD_DOWN = 0;
    /**
     * @return string the associated database table name
     */
    const ADVICE_TYPE_CONTENT = 'content';
    const ADVICE_TYPE_TOPIC = 'topic';

    public $time_begin;
    public $time_end;
    public $searchKey;
    private static $_options;
    public $extids;


    public function tableName()
    {
        return 'advice';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
        return array(
            array('upload, weight, time_upload, time_create, time_update', 'numerical', 'integerOnly' => true),
            array('name', 'length', 'max' => 64),
            array('name', 'unique'),
            array('weight', 'length', 'max' => 32),
            array('id, name,type,upload, weight, time_upload, time_create, time_update', 'safe', 'on' => 'search'),
            array('time_begin, time_end,id,extids,searchKey', 'safe'),
        );
    }

    protected function afterFind()
    {
        $this->extids = array_map(function (AdviceExt $ext) {
            return $ext->ext_id;
        }, $this->advice_exts);
        parent::beforeFind(); // TODO: Change the autogenerated stub
    }


    protected function beforeDelete()
    {
        foreach ($this->advice_exts as $ext) {
            if ($ext) {
                $ext->delete();
            }
        }
        return parent::beforeDelete(); // TODO: Change the autogenerated stub
    }


    public static function getOptions($attribute, $options = array())
    {
        if (!isset(self::$_options[$attribute])) {
            $opts = [];
            switch ($attribute) {
                case 'upload':
                    $opts[self::UPLOAD_DOWN] = '下线';
                    $opts[self::UPLOAD_UPLOAD] = '上线';
                    break;
            }
            self::$_options[$attribute] = $opts;
        }
        if (is_array($options) && !empty($options)) {
            foreach (self::$_options[$attribute] as $k => $v) {
                $options[$k] = $v;
            }
        } else {
            $options = self::$_options[$attribute];
        }
        return $options;
    }


    /**
     * @return array relational rules.
     */
    public function relations()
    {
        return array('advice_exts' => array(self::HAS_MANY, 'AdviceExt', ['aid' => 'id'],'order'=>'weight'),);
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'name' => '名称',
            'type' => '类型',
            'upload' => '是否上线',
            'weight' => '权重',
            'time_upload' => 'Time Upload',
            'time_create' => 'Time Create',
            'time_update' => 'Time Update',
            'extids' => '选择推荐',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
// @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('type', $this->type, false);
        $criteria->compare('id', $this->id, true);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('upload', $this->upload);
        $criteria->compare('weight', $this->weight);
        $criteria->compare('time_upload', $this->time_upload);
        $criteria->compare('time_create', $this->time_create);
        $criteria->compare('time_update', $this->time_update);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Advice the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    protected function afterSave()
    {
        $this->updateLink();
        parent::afterSave(); // TODO: Change the autogenerated stub
    }

    private function updateLink()
    {
        if ($this->extids || $this->extids==[]) {
            foreach ($this->advice_exts as $ext) {
                $ext->delete();
            }
            foreach ($this->extids as $sid) {
                $advice_ext = AdviceExt::build($this->id, $sid, $this->type);
                if ($advice_ext) {
                    $advice_ext->save();
                } else {
                    throw new Exception('save failed', 1);
                }

            }
        }
    }

    public function searchByKey()
    {
        $criteria = new CDbCriteria;
        if (isset($_GET['Advice_sort'])) {
            $criteria->order = str_replace('.', ' ', $_GET['Advice_sort']);
        } else {
            $criteria->order = 'upload desc , weight desc';
        }

        if (!empty($ts_begin = strtotime($this->time_begin))) {
            $criteria->addCondition('`time_create` >= ' . $ts_begin);
        }
        if (!empty($ts_end = strtotime($this->time_end))) {
            $criteria->addCondition('`time_create` <= ' . $ts_end);
        }

        if ($this->searchKey !== '') {
            $criteria->compare('name', $this->searchKey, true);
        }
        $criteria->compare('type', $this->type, false);
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => 5,
            ),
        ));
    }

    public function isUpload()
    {
        return $this->upload == 1;

    }

    public function upload()
    {
        if (!$this->isUpload()) {
            self::model()->updateAll(['upload' => self::UPLOAD_DOWN],'type =:type',[':type'=>$this->type]);
            $this->upload = self::UPLOAD_UPLOAD;
            $this->save();
        } else {
            $this->upload = self::UPLOAD_DOWN;
            $this->save();
        }
        return true;
    }

}
